package com.yuanjin.activity;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.yuanjin.R;
import com.yuanjin.adapter.ChatText_Adapter;
import com.yuanjin.util.ListData_tulingChat;
import com.yuanjin.util.LoaddataThread;
import com.yuanjin.util.YuanJin_Application;
import com.yuanjin.util.SQLiteHelper;
import com.yuanjin.util.Yuanjin;
import com.yuanjin.widget.RefreshListView;
import com.yuanjin.widget.RefreshListView.IRefreshListener;

public class CopyOfChatArea3 extends FriendsListActivity implements IRefreshListener {
	private SQLiteHelper helper;
	private Button btnsend;
	private TextView tv_name;
	private EditText et_content;
	private RefreshListView listview_chat;
	boolean stopThread = false;
	String name = "";
	String data = "";
	int sum = 0;
	private List<ListData_tulingChat> lists;
	private ChatText_Adapter adapter;
	private ProgressBar mProgressBar;
	static int xixi = 0;
	static int ii = 0;
	private boolean inputShowflag = true;// 设置需要监听界面变化
	private Cursor cursor;
	private int count;// 本地数据库总数目
	private int refreshcount = 1;// 下拉刷新次数
	private int interval = 10;// 每次下拉刷新取出的数据量
	private Vector<Object> vector = new Vector<Object>();// 用于保存下拉刷新数据
	private boolean refresh_finish = false;

	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.chattingarea2);
		initView();
		// getContentThread();
		// TestThread();

	}

	private void TestThread() {

		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				// Cursor cursor = helper.queryAll();
				int index = 0;
				// while (cursor.moveToNext()) {
				while (!stopThread) {
					try {
						// 每隔一秒向服务器发出数据更新探询
						Thread.sleep(2500);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					index++;

					Log.e("chatting",
							"线程正在每隔10秒执行一次aaaaa" + Integer.toString(index));

					// Cursor cursor = helper.queryAll();
					// while (cursor.moveToNext()) {
					// Log.e("数据库查询输出-content", cursor.getString(cursor
					// .getColumnIndex("content")));
					// Log.e("数据库查询输出-datesecond", Integer.toString(cursor
					// .getInt(cursor.getColumnIndex("datesecond"))));
					// Log.e("数据库查询输出-username", cursor.getString(cursor
					// .getColumnIndex("username")));
					// }

				}
			}
		});
		thread.start();
	}

	private void initView() {
		btnsend = (Button) findViewById(R.id.send_btn);
		// tv_name = (TextView) findViewById(R.id.tv_friendsname);
		et_content = (EditText) findViewById(R.id.sendText);
		listview_chat = (RefreshListView) findViewById(R.id.listview_chat);
		final View activityRootView = findViewById(R.id.activityRoot);
		Intent intent = getIntent();
		name = intent.getStringExtra("friendsname");

		et_content.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (inputShowflag) {
					onClickEditText();
				}

			}
		});

		// 发送按钮添加点击监听事件
		btnsend.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				onClicksendMessage();
			}
		});

		lists = new ArrayList<ListData_tulingChat>();
		adapter = new ChatText_Adapter(lists, this);
		listview_chat.setAdapter(adapter);

		// 设置下拉刷新监听
		listview_chat.setInterface(this);

		// 创建数据表
		helper = new SQLiteHelper(this);
		/* 初始化显示数据，先对本地数据库进行查询，若>=10条记录则显示10条记录（下拉刷新也是每次10条），小于10条则显示全部 */
		cursor = helper.queryAll();
		count = cursor.getCount();// 得到本地数据库的记录总数

		// for (ii = 0; ii < 5; ii++) {
		// ListData_tulingChat listdata = new ListData_tulingChat("哈哈",
		// ListData_tulingChat.SEND, Yuanjin.getTime());
		// lists.add(listdata);
		// adapter.notifyDataSetChanged();
		//
		// }

	}

	protected void onClickEditText() {
		Toast.makeText(this, "接收到监听事件了", Toast.LENGTH_SHORT).show();
		Log.e("activityRootView.getHeight()",
				Integer.toString(listview_chat.getLastVisiblePosition()));
		System.out.println("listview_chat.getLastVisiblePosition()= "
				+ listview_chat.getLastVisiblePosition());
		if (listview_chat.getLastVisiblePosition() > 9) {
			inputShowflag = false;
			listview_chat.setStackFromBottom(true);
			listview_chat
					.setTranscriptMode(ListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
		}

	}

	@SuppressLint("NewApi")
	private void onClicksendMessage() {

		// 获取发送内容
		String content = et_content.getText().toString();
		// 去除输入内容的纯空格或者回车，即完全没有文字输入的情况
		String con = content.trim();
		// 获取发送的时间秒数
		int currentTimeSecond = 0;
		String dateTime = "";

		// 输入信息是否为空判断
		if (!(con == null || con.isEmpty())) {
			// 每发送成功一句，本地的数据量值就要自增1
			YuanJin_Application.message_sum = Integer.toString(Integer
					.parseInt(YuanJin_Application.message_sum) + 1);
			// 调用System.currentTimeMillis()方法，可以取得从1970年1月1日开始经过的毫秒数。实际操作使用秒即可
			currentTimeSecond = (int) (System.currentTimeMillis() / 1000);
			ListData_tulingChat listdata = new ListData_tulingChat(content,
					ListData_tulingChat.SEND, Yuanjin.getTime());
			lists.add(listdata);
			// 在有新的数据产生后对数据进行重新适配
			adapter.notifyDataSetChanged();
			// 更改
			ii++;
			// Log.e("到这里了","哈哈");
			// listview_chat.post(new Runnable() {
			// public void run() {
			// Log.e("到这里了","嘻嘻");
			// Log.e("LastVisiblePosition", Integer.toString(listview_chat
			// .getLastVisiblePosition()));
			// Log.e("firstVisiblePosition", Integer
			// .toString(listview_chat.getFirstVisiblePosition()));
			//
			// }
			//
			//
			// });
			// Log.e("LastVisiblePosition2", Integer.toString(listview_chat
			// .getLastVisiblePosition()));

			// 发送信息后将输入框清空
			et_content.setText("");

			// 存信息到本地聊天记录表
			// insert(int date, String datesecond, String content,String
			// username)
			helper.insert(dateTime, currentTimeSecond, content, YuanJin_Application.username);

			/********************* 向服务器上传数据 ***************************/
			// " datesecond INTEGER," + " date VARCHAR(20),"
			// + " content TEXT)";
			// 上传服务器的账号、密码等信息
			Map<String, String> map = new HashMap<String, String>();
			// map.put("datesecond", Integer.toString(currentTimeSecond));
			map.put("date", dateTime);
			map.put("content", content);
			map.put("username", YuanJin_Application.username);
			// 上传服务器的调用方法地址
			String path = "http://1.zhan414.sinaapp.com/?/index.php?c=main&a=store_chatmessage";

			// 开启上传线程
			LoaddataThread loaddataThread = new LoaddataThread(map, handler,
					path);
			loaddataThread.start();

		} else {
			// 若没有输入信息，则提示
			Toast.makeText(this, "请输入信息。。", Toast.LENGTH_SHORT).show();
		}
	}

	private void getContentThread() {
		// 开启线程不断的访问服务器，以了解好友是否发来信息。实际上如果是socket通信的话则不会这么麻烦
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				int index = 0;
				// TODO Auto-generated method stub
				while (!stopThread) {
					try {
						// 每隔一秒向服务器发出数据更新探询
						Thread.sleep(5000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					index++;
					Log.e("chatting",
							"下载数据线程正在每隔2秒执行一次" + Integer.toString(index));

					/*********************
					 * 向服务器上传数据
					 ***************************/
					// " datesecond INTEGER," + " date VARCHAR(20),"
					// + " content TEXT)";
					// 上传服务器的账号、密码等信息
					Map<String, String> map = new HashMap<String, String>();
					// map.put("datesecond", currentTimeSecond);
					map.put("date", "11");
					map.put("content", "r#");
					map.put("message_sum", YuanJin_Application.message_sum);
					// 上传服务器的调用方法地址
					String path = "http://1.zhan414.sinaapp.com/?/index.php?c=main&a=store_chatmessage";
					// Log.e("message", "getContentThread 到这里都没错");
					// 开启上传线程
					LoaddataThread loaddataThread = new LoaddataThread(map,
							handler, path);
					loaddataThread.start();
					// Cursor cursor = helper.queryAll();
					// while (cursor.moveToNext()) {
					// cursor.getPosition();
					// Log.e("数据库查询输出-cursor_count:",
					// Integer.toString(cursor.getCount()) + "当前位置："
					// + Integer.toString(cursor.getCount()));
					// Log.e("数据库查询输出-content", cursor.getString(cursor
					// .getColumnIndex("content")));
					// Log.e("数据库查询输出-datesecond", Integer.toString(cursor
					// .getInt(cursor.getColumnIndex("datesecond"))));
					// Log.e("数据库查询输出-username", cursor.getString(cursor
					// .getColumnIndex("username")));
					// }
				}
			}

		});
		thread.start();
	}

	// handler接收数据
	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case 6:
				/*
				 * receiveData:服务器传过来的用户数据 receiveData_Sum：用户数据的数目
				 */
				// returndata=usercontent+"***"+username+"***"+time;
				data = (String) msg.obj;
				sum = msg.arg1;
				Log.e("ChatArea3-handler-data:  ", data);
				YuanJin_Application md = (YuanJin_Application) getApplication();
				md.setReceiveData(data);
				// md.setReceiveData_Sum(sum);
				YuanJin_Application.message_sum = Integer.toString(sum);
				// Log.e("本地数据表记录总数", data);
				Vector<Object> dataVector = new Vector<Object>(
						Arrays.asList(data.split("@@@")));
				String usercontent = dataVector.get(0).toString();
				// 第1段则为存储了数据的字符串段
				String username = dataVector.get(1).toString();
				// 第2段则为存储了用户名数据的字符串段
				String time = dataVector.get(2).toString();
				// 第3段则为存储了时间数据的字符串段
				// 将字符串转换为数组--提取用户数据分别存储
				String[] contentArray = usercontent.split("###");
				String[] usernameArray = username.split("###");
				String[] timeArray = time.split("###");

				// for (int i = 0; i < contentArray.length; i++) {
				// Log.e("数组内容显示", "contentArray[" + i + "]" + contentArray[i]);
				//
				// }
				// for (int i = 0; i < usernameArray.length; i++) {
				// Log.e("数组内容显示", "usernameArray[" + i + "]"
				// + usernameArray[i]);
				//
				// }
				// for (int i = 0; i < timeArray.length; i++) {
				// Log.e("数组内容显示", "usernameArray[" + i + "]" + timeArray[i]);
				//
				// }
				// 接收到数据，先进行判断是否有新的数据加入，若有新数据，则将其加入聊天数据库，并显示；否则不进行操作
				// 判断依据就是数据的数目

				// 测试：不进行数目判断，看是否能将数据添加进数据库

				// Cursor cursor = helper.queryAll();
				// // 获取本地聊天记录表的数据总数count
				// int localcount = cursor.getCount();
				// Log.e("本地数据表记录总数", Integer.toString(localcount));
				// while (cursor.moveToNext()) {
				// Log.e("数据库查询输出-content",
				// cursor.getString(cursor.getColumnIndex("content")));
				// Log.e("数据库查询输出-datesecond", cursor.getString(cursor
				// .getColumnIndex("datesecond")));
				// }

				/********************** 显示服务器端下载数据 ****************************/
				ListData_tulingChat listdata;
				int tag = 0;// 接受或发送方标志
				for (int j = 0; j < contentArray.length; j++) {

					// 对是否是自己发出的信息就行判断，已决定显示的样式
					if (usernameArray[j].equals(YuanJin_Application.username)) {
						tag = ListData_tulingChat.SEND;
					} else {
						tag = ListData_tulingChat.RECEIVER;
					}
					listdata = new ListData_tulingChat(contentArray[j], tag,
							Yuanjin.getTime());
					lists.add(listdata);
				}

				// 在有新的数据产生后对数据进行重新适配
				adapter.notifyDataSetChanged();
				break;
			case 8:
				sum = msg.arg1;
				YuanJin_Application.message_sum = Integer.toString(sum);
				Log.e("logtest_firstin",
						"/******************* case 8 **********************/"
								+ YuanJin_Application.message_sum);
				break;

			default:
				break;
			}
		}
	};

	// 聊天页面退出
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		stopThread = true;
		Log.e("chatting", "聊天页面退出了");
	}

	// 下拉刷新操作
	@Override
	public void onRefresh() {

		handler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// int hahah = 0;
				//
				// for (int i = 0; i < 5; i++) {
				// hahah++;
				// xixi++;
				// ListData_tulingChat listdata = new ListData_tulingChat("哈哈"
				// + Integer.toString(xixi), ListData_tulingChat.SEND,
				// Yuanjin.getTime());
				// lists.add(0, listdata);
				// adapter.notifyDataSetChanged();
				// }
				// listview_chat.setSelectionFromTop(hahah + 1, listview_chat
				// .getChildAt(hahah).getHeight() / 2);
				// listview_chat.refreshComplete();
				if (!refresh_finish) {
					vector.clear();// 每次使用前都清除一次数据
					System.out.println("cout= " + count);
					if ((count - (1 + 10 * refreshcount)) > 0) {
						cursor.moveToPosition(count - (1 + 10 * refreshcount));
						interval = 10;
					} else {// 说明记录取完了
						cursor.moveToPosition(-1);
						interval = count - (1 + 10 * (refreshcount - 1))+1;
						refresh_finish = true;
					}

					// 有数据且<=10条
					while (cursor.moveToNext() && interval > 0) {
						// ar[ic] =
						// cursor.getString(cursor.getColumnIndex("content"));
						vector.add(cursor.getString(cursor
								.getColumnIndex("content")));
						cursor.getPosition();
						Log.e("数据库查询输出-cursor_count:",
								Integer.toString(cursor.getCount()) + "当前位置："
										+ Integer.toString(cursor.getCount()));
						Log.e("数据库查询输出-content", cursor.getString(cursor
								.getColumnIndex("content")));
						Log.e("数据库查询输出-datesecond", Integer.toString(cursor
								.getInt(cursor.getColumnIndex("datesecond"))));
						Log.e("数据库查询输出-username", cursor.getString(cursor
								.getColumnIndex("username")));
						interval--;
					}
//					if (refresh_finish) {// 为true时说明记录取尽，仍有最后一条记录未取出
//						cursor.moveToFirst();
//						vector.add(cursor.getString(cursor
//								.getColumnIndex("content")));
//					}
					for (int j = vector.size() - 1; j >= 0; j--) {
						Log.e("vector-content", Integer.toString(j) + "   "
								+ vector.get(j).toString());
					}

					refreshcount++;
					listview_chat.refreshComplete();
				} else {
					listview_chat.refreshComplete();
					Toast.makeText(CopyOfChatArea3.this, "没有更多记录了",
							Toast.LENGTH_SHORT).show();
				}
				Log.e("test", Boolean.toString(refresh_finish));
			}
		}, 2000);
	}
	
	

	
}
